from odoo import fields, models, api

from ..functions.aliyun_oss_bucket import AliyunOSSBucket


class ResConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    aliyun_oss_enabled = fields.Boolean(string="阿里云存储是否开启", config_parameter='aliyun_oss.enabled')
    aliyun_oss_connected = fields.Boolean(string='阿里云存储是否连接', config_parameter='aliyun_oss.connected', help='用于检测是否连接成功')

    aliyun_oss_endpoint = fields.Char(string="阿里云存储Endpoint", config_parameter='aliyun_oss.endpoint')
    aliyun_oss_bucket_name = fields.Char(string="阿里云存储Bucket Name", config_parameter='aliyun_oss.bucket_name')
    aliyun_oss_access_key_id = fields.Char("阿里云存储AccessKey ID", config_parameter='aliyun_oss.accessKey_id')
    aliyun_oss_access_key_secret = fields.Char("阿里云存储AccessKey Secret", config_parameter='aliyun_oss.accessKey_secret')

    selected_ir_model_ids = fields.Char(string='模型', config_parameter='aliyun_oss.selected_ir_model_ids', copy=False)

    @api.onchange('aliyun_oss_enabled')
    def _onchange_aliyun_oss_enabled(self):
        if not self.aliyun_oss_enabled:
            self.update({'aliyun_oss_connected': False,
                         'aliyun_oss_endpoint': False,
                         'aliyun_oss_bucket_name': False,
                         'aliyun_oss_access_key_id': False,
                         'aliyun_oss_access_key_secret': False})

    def test_for_aliyun_oss_connect(self):
        """ 测试连接 """
        bucket = AliyunOSSBucket(self.env).get_aliyun_oss_bucket()
        if bucket:
            self.update({'aliyun_oss_connected': True})
        else:
            self.update({'aliyun_oss_connected': False})
